import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

import axios from "axios";
import vuexPersist from "vuex-persist";

export default new Vuex.Store({
  state: {
    msg: "这是vuex里的公共数据msg",
    num: 10,
    list: [
      { name: "崔猛", q: "扫地", w: "迟到", e: "唱歌", age: 18 },
      { name: "崔猛2", q: "扫地", w: "迟到", e: "反向抽烟", age: 35 },
      { name: "崔猛3", q: "扫地", w: "迟到", e: "反向抽烟", age: 69 },
      { name: "崔猛4", q: "扫地", w: "迟到", e: "反向抽烟", age: 22 },
    ],
    data: [],
  },

  mutations: {
    aa(state) {
      state.num++;
    },
    adds(state, obj) {
      console.log(obj);
      state.list.push(obj);
    },
    remove(state, i) {
      state.list.splice(i, 1);
    },

    setdata(state, val) {
      state.data = val;
    },
    //把 接受到的请求到的json数据赋值给data
  },
  actions: {
    getdata(context) {
      // context就是整个仓库
      axios.get("data.json").then((res) => {
        console.log(res);
        context.commit("setdata", res.data.list);
        //只有mutation能操作state，action也没有权力操作state，所以只能调用mutation操作
      });
    },
  },
  modules: {},
  getters: {
    all(state) {
      let num = 0;
      state.list.forEach((item) => {
        num += item.age;
      });
      return num;
    },
  },

  plugins: [
    new vuexPersist({
      storage: window.localStorage,
    }).plugin,
  ],
  //插件
});

// state 状态 就是数据的意思相当于是data
// mutation 是修改的意思 用来操作state 而且 state只能在mutation中操作

// getters 就相当于是计算属性,跟计算属性的区别是 计算属性只在当前页面使用  getters可以在任何组件使用
